const app = getApp();
const webimhandler = require('../../utils/webim_handler');
import { getUserInfo } from '../../../common/utils/ws/wsxcx-opendata-sdk';

Page({
  data: {
    roomName: '',
    isFocus: true,
    imgPathArray: [],
    count: 1,
    title: '',
    anchor: '',
    roomBackground: '',
    successImgPaths: [],
    modeArray: [{
        name: '标清',
        value: 'SD',
      checked: true,
      },
      {
        name: '高清',
      value: 'HD',
      },
      {
        name: '超清',
      value: 'FHD',
      },
    ],
    orientationArray: [{
        name: '竖屏',
        value: 'vertical',
      checked: true,
      },
      {
        name: '横屏',
      value: 'horizontal',
      },
    ],
    mode: 'SD', //默认标清
    orientation: 'vertical', //默认竖屏
    enableCamera: true, //默认开启摄像头
    supportChat: false,
    virtualNumber: '',  // 虚拟人数
  },
  onLoad() {
    this.isChatSupport().then(supportChat => {
      this.setData({ supportChat });
    });
  },
  isChatSupport() {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'entry/wxapp/index',
        data: {
          op: 'is_chat',
        },
        module: 'cm_lvb',
        success: res => {
          resolve(res.data && res.data.data && res.data.data.is_chat == 1);
        },
        fail: () => {
          resolve(false);
        },
      });
    });
  },
  createGroup(title) {
    return new Promise((resolve, reject) => {
      if (this.data.supportChat) {
        webimhandler.createBigGroup({
          roomName: title || '直播间',
        }, ({ errCode, errMsg, ret }) => {
          if (errCode) {
            console.log('IM建群失败,', errMsg);
            reject(Error(errMsg));
          } else {
            console.log('IM建群成功,', ret);
            webimhandler.applyJoinBigGroup(ret.GroupId, ({ errCode, errMsg, callback }) => {
              if (errCode) {
                console.log('IM进群失败,', errMsg);
                reject(Error(errMsg));
              } else {
                console.log('IM进群成功');
                resolve(ret);
              }
            });
          }
        });
      } else {
        resolve();
      }
    });
  },
  createLiveRoom() {
    getUserInfo().then(userInfo => {
    let {
        title = '',
        anchor = '',
        successImgPaths = '',
        virtualNumber: virtual = 0,
        roomBackground = '',
    } = this.data;
   
    if (!anchor) {
        anchor = userInfo.nickName;
    } else if (this.data.supportChat) {
      webimhandler.setNickName(anchor, function (ret) {
        if (ret.errCode) {
          console.log('修改昵称失败', ret);
        } else {
          console.log('修改昵称成功');
        }
      });
    }

    if (!title || (/[<>*{}()^%$#@!~&= ]/.test(title))) {
      wx.showModal({
          title: '系统提示',
        content: '房间名称不能为空或包含特殊字符',
        showCancel: false,
      });
      return;
    }
    if (successImgPaths.length <= 0) {
      wx.showModal({
          title: '系统提示',
        content: '请上传房间封面图',
        showCancel: false,
      });
      return;
    }

    virtual = virtual === '' ? 0 : virtual;

    let cover = successImgPaths[0];
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'createRoom',
      },
      module: 'cm_lvb',
      success: res => {
          console.log('==========7262727882', res);
          
        // 预创建成功
        if (res.data.data.errcode === -1) { //可能房间分配完了
          wx.showModal({
            title: '系统提示',
            content: res.data.data.errmsg,
            success:res=>{
              if (res.confirm) {
                wx.navigateBack({});
              }
            },
          });
          return;
        }
        let {
            id = '',
            pushdomain = '',
            roomid = '',
            playdomain = '',
            playdomain_high: playdomainHigh = '',
        } = res.data.data && res.data.data.room;
        let {
          mode,
          orientation,
          enableCamera,
        } = this.data;

        if (!id && !pushdomain) {
          wx.showModal({
            title: '系统提示',
            content: '直播间创建失败',
            showCancel: false,
            success: res => {
              wx.navigateTo({}); // 预创建失败直接返回上一页
            },
          });
          return;
        }

        this.createGroup(title).then((ret) => {
        app.util.request({
          url: 'entry/wxapp/index',
          data: {
            op: 'updateRoom',
            id,
            title,
            anchor,
            cover,
              group_id: ret && ret.GroupId,
                virtual,
          },
          module: 'cm_lvb',
          success: res => {
            enableCamera = enableCamera ? 1 : 0;
            console.log('===============studio createLiveRoom 直播间创建成功', res);
            console.log('===============studio createLiveRoom 当前画面画质', mode);
            console.log('===============studio createLiveRoom 当前画面方向', orientation);
            console.log('===============studio createLiveRoom 是否开启摄像头', enableCamera);
            app.util.navigateTo('cm_lvb/pages/push/push', {
              id,
              roomid,
              title,
                      anchor,
                  pushUrl: pushdomain,//默认高清
              mode,
              orientation,
              enableCamera,
                  anchorAvatar: userInfo && userInfo.avatarUrl || '',
                  groupID: ret && ret.GroupId || '',
                  playdomain,
                  playdomainHigh,
                  roomBackground,
            }, true);
          },
        });
        }).catch(err => {
          console.log(err);
        });
      },
      fail: res => {
        // 预创建房间失败
        console.log(res);
      },
    });
    }).catch(res => {
      app.util.navigateTo('/cm_lvb/pages/auth/auth');
    });
  },
  setAnchor(e) {
    this.setData({
      anchor: e.detail.value,
    });
  },
  setTitle(e) {
    this.setData({
      title: e.detail.value,
    });
  },
  checkMaxCount() {
    let {
      imgPathArray,
      count,
      disableImgUpload,
    } = this.data;
    disableImgUpload = imgPathArray.length >= count ? true : false;
    this.setData({
      disableImgUpload,
    });
  },
  previewImage(e) {
    let urls = [];
    let {
      imgPathArray,
    } = this.data;
    let {
      path: current,
    } = e.currentTarget.dataset.item;
    imgPathArray.map(imgItem => {
      urls.push(imgItem.path);
    });
    wx.previewImage({
      current,
      urls,
    });
  },
  removeImage(e) {
    const {
      delindex,
    } = e.currentTarget.dataset;
    let {
      imgPathArray,
    } = this.data;
    wx.showModal({
      title: '是否删除?',
      success: res => {
        if (res.confirm) {
          imgPathArray.splice(delindex, 1);
          this.setData({
            imgPathArray,
          });
          this.checkMaxCount();
        }
      },
    });
  },
  chooseImage() {
    let {
      imgPathArray,
      count,
    } = this.data;
    wx.chooseImage({
      count,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        res.tempFiles.map(imgItem => {
          imgPathArray.push(imgItem);
        });
        if (imgPathArray.length >= count) {
          imgPathArray = imgPathArray.splice(0, count);
        }
        this.setData({
          imgPathArray,
        });
        this.uploadImage();
        this.checkMaxCount();
      },
    });
  },
  uploadImage() {
    let successImgPaths = [];
    let {
      imgPathArray,
    } = this.data;
    let url = app.util.url('utility/file/upload', {
      type: 'image',
      thumb: '0',
    });
    imgPathArray.map(imgItem => {
      wx.showLoading({
        title: '图片上传中',
        icon: 'loading',
        mask: true,
      });
      wx.uploadFile({
        url,
        filePath: imgItem.path,
        name: 'file',
        success: res => {
          if (this.isJSON(res.data)) {
            console.log('=========res.data', res.data);
            
            let data = JSON.parse(res.data);
            successImgPaths.push(data.filename);
            if (successImgPaths.length === imgPathArray.length) {
              wx.hideLoading();
              console.log('=========successImgPaths', successImgPaths);
              this.setData({
                successImgPaths,
                roomBackground: data.url,
              });
            }
          }
        },
        fail: res => {
          wx.hideLoading();
          wx.showModal({
            title: '系统提示',
            content: '上传失败',
          });
        },
      });
    });
  },
  isJSON(str) {
    if (typeof str === 'string') {
      try {
        let obj = JSON.parse(str);
        if (typeof obj === 'object' && obj) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
    }
  },
  changeMode(e) {
    console.log('======当前画面画质:', e.detail.value);
    this.setData({
      mode: e.detail.value,
    });
  },
  changeOrientation(e) {
    console.log('======当前画面方向:', e.detail.value);
    this.setData({
      orientation: e.detail.value,
    });
  },
  changeCamera(e) {
    let enableCamera = e.detail.value ? 1 : 0;
    console.log('======开启摄像头:', enableCamera);
    this.setData({
      enableCamera,
    });
  },
  setVirtualNumber(e) {
    this.setData({
      virtualNumber: e.detail.value,
    });
  },
});
